<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addCate">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 树状表 -->
      <tree-tabel
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
        :show-row-hover="false"
        :data="cateList"
        :columns="columns"
        class="treeTabel"
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-error" style="color: red" v-if="scope.row.cat_deleted"></i>
          <i class="el-icon-success" style="color: lightgreen" v-else></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag size="mini" v-else-if="scope.row.cat_level === 1" type="success">二级</el-tag>
          <el-tag size="mini" v-else type="warning">三级</el-tag>
        </template>
        <!-- 操作区域 -->
        <template slot="operate" slot-scope="scope">
          <el-button type="primary" class="el-icon-edit" @click="editCate(scope.row.cat_id)">编辑</el-button>
          <el-button type="danger" class="el-icon-delete" @click="delBtn(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-tabel>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryIfo.pagenum"
        :page-sizes="[3, 5, 8, 12]"
        :page-size="queryIfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 点击编辑的弹出层 -->
    <el-dialog title="编辑分类" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="cateInfo" ref="cateForm" :rules="CateRules" label-width="100px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="cateInfo.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="editDialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="editCateInfoDialogVisible">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加按钮弹出层 -->
    <el-dialog title="添加分类" :visible.sync="addCateDialogVisible" width="60%" @close="addCateDialogClosed">
      <el-form :model="classifyForm" :rules="CateRules" ref="cateForm" label-width="100px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="classifyForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- 级联选择器 -->
          <el-cascader
            v-model="selectedKeys"
            :options="parentCateList"
            :props="cascaderProps"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="addCateDialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="addCateBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      //   查询参数
      queryIfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isok'
        },
        {
          label: '排序',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          template: 'operate'
        }
      ],
      editDialogVisible: false,
      addCateDialogVisible: false,
      // 添加分类的提交表单
      classifyForm: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      CateRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur' }
        ]
      },
      selectedKeys: [],
      parentCateList: [],
      // 级联选择器的配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 修改分类名称后保存的表单
      cateInfo: {
        cat_name: '',
        cat_id: 0
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories', { params: this.queryIfo })
      if (res.meta.status !== 200) return this.$message.error('获取数据失败!')
      this.total = res.data.total
      this.cateList = res.data.result
    },
    async delBtn(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (confirmResult !== 'confirm') return this.$message.info('取消了删除!')
      const { data: res } = await this.$http.delete('categories/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除分类失败!')
      this.$message.success('删除分类成功!')
      this.getCateList()
    },
    // 点击编辑按钮先获取到分类信息并存储
    async editCate(id) {
      const { data: res } = await this.$http.get('categories/' + id)
      this.cateInfo = res.data
      this.editDialogVisible = true
    },
    async editCateInfoDialogVisible() {
      const { data: res } = await this.$http.put('categories/' + this.cateInfo.cat_id, { cat_name: this.cateInfo.cat_name })
      if (res.meta.status !== 200) return this.$message.error('修改分类名称失败！')
      this.$message.success('修改分类名称成功!')
      this.editDialogVisible = false
      this.getCateList()
    },
    // size发生变化立即调用
    handleSizeChange(newSize) {
      this.queryIfo.pagesize = newSize
      this.getCateList()
    },
    // 页码值发生变化立即调用
    handleCurrentChange(newPage) {
      this.queryIfo.pagenum = newPage
      this.getCateList()
    },
    addCate() {
      this.getParentCateList()
      this.addCateDialogVisible = true
    },
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', { params: { type: 2 } })
      if (res.meta.status !== 200) return this.$message.error('获取数据失败!')
      this.parentCateList = res.data
    },
    // 选中父级分类的节点 触发事件函数
    handleChange() {
      // 判断是否选中父级列表中的值
      if (this.selectedKeys.length > 0) {
        this.classifyForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
        this.classifyForm.cat_level = this.selectedKeys.length
      } else {
        this.classifyForm.cat_pid = 0
        this.classifyForm.cat_level = 0
      }
    },
    addCateDialogClosed() {
      this.$refs.cateForm.resetFields()
      this.selectedKeys = []
      this.classifyForm.cat_level = 0
      this.classifyForm.cat_pid = 0
    },
    addCateBtn() {
      this.$refs.cateForm.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('categories', this.classifyForm)
        if (res.meta.status !== 201) return this.$message.error('添加分类失败!')
        this.$message.success('添加分类成功!')
        this.addCateDialogVisible = false
        this.getCateList()
      })
    }
  }
}
</script>

<style lang="less" scoped>
.treeTabel {
  margin: 15px 0;
}
.el-cascader {
  width: 100%;
}
</style>
